# -*- coding: utf-8 -*- 

import json
import uuid
import os
import subprocess
import time
import threading
import logging
import struct
 
import socket

from socketIO_client import SocketIO

from threading import Thread
# import moniterFace
import platform
import models
import requests
import rtmpPush
import base64
g_host = '127.0.0.1'
# g_host = 'cgdemo.kjdashi.com'
# g_host = 'gmcg.kjdashi.com'
g_port = 8000

g_face_host = 'cgdemo.kjdashi.com'
#g_face_host = 'cgio.visualdeep.com'
g_face_port =8002 

g_localTypeList=['CP','RL']
macId = 'HS001'
padSid = ''
uploadUlr = 'http://cg.visualdeep.com:18200/CityInspectors'
# uploadUlr = 'http://192.168.190.106:8080/CityInspectors'
#--------websocket--------
def sendPro(protocolId,sendData):
	sendData['protocol'] = protocolId
	sendData['sid'] = padSid
	global socketIO
	socketIO.emit('CC', sendData)

def on_connect():
	logging.info('socketIO is connected')
	global socketIO
	socketIO.emit('CT', 'CC')
def on_disconnect():
	logging.info('socketIO is disconnect')
def on_reconnect():
	logging.info('socketIO is reconnect') 
	global socketIO
	socketIO.emit('CT', 'CC')

def on_APP(*args):
	if args[0]['protocol']=='W01':
		global padSid
 		padSid = args[0]['sid']




#------------faceSocketIO

def sendFacePro(protocolId,sendData):
	sendData['protocol'] = protocolId
	sendData['sid'] = padSid
	global faceSocketIO
	faceSocketIO.emit('CDD', sendData)

def on_face_connect():
	logging.info('socketIO is connected')
	global faceSocketIO
	faceSocketIO.emit('CT', 'CDD')
	faceSocketIO.emit('CDD', {'protocol':'L01','cid':macId})
	faceSocketIO.emit('CDD', {'protocol':'C01','cid':macId,'type':g_localTypeList,'ip':getIpforSys()})
def on_face_disconnect():
	logging.info('socketIO is disconnect')
def on_face_reconnect():
	logging.info('socketIO is reconnect') 
	global faceSocketIO
	faceSocketIO.emit('CT', 'CDD')
	faceSocketIO.emit('CDD', {'protocol':'L01','cid':macId})
	faceSocketIO.emit('CDD', {'protocol':'C01','cid':macId,'type':g_localTypeList,'ip':getIpforSys()})

	
	
def on_face_CC(*args):

	logging.info('收到'+str(args[0]['protocol'])+' 协议') 
	if args[0]['protocol']=='S01':
		logging.info('收到'+str(args[0]['protocol'])+' 协议') 
	elif args[0]['protocol']=='H12':
		logging.info('收到'+str(args[0]['protocol'])+' 协议') 
		resCheckFace(args[0])
	elif args[0]['protocol']=='S05':#开始推流
		rtmpPush.cddPushRtmp(args[0])
 	elif args[0]['protocol']=='S06':#停止推流
 		rtmpPush.cddStopRtmp(args[0])
 	elif str(args[0]['protocol'])=='S10':
		logging.warn('heheda')
		res = pullFaceBlackHttp(macId)
		logging.warn(res)
	elif args[0]['protocol']=='S11':
		res = pullPlateBlackHttp(macId)
		print(res)


def getip():
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		s.connect(('8.8.8.8', 0))
		ip = s.getsockname()[0]
	except:
		ip = "x.x.x.x"
	finally:
		s.close()
		return ip
 
def getIpforSys():
	sysstr = platform.system()
	if sysstr == "Windows":
		ip_address = socket.gethostbyname(socket.gethostname())
		return ip_address
	elif sysstr == "Linux":
		ip_address = getip()
		return ip_address
	elif sysstr == "Darwin":
		ip_address = socket.gethostbyname(socket.gethostname())
		return ip_address
	else:
		return "0.0.0.0"


def resCheckFace(requestMap):
	# checkId = requestMap['checkId']
	# point = requestMap['points']
	# imageList = requestMap['imageList']
	sendData = {}
	sendData['list'] = []
	for data in requestMap['res']:
		if float(data['points']) >= 0.4:
			print 'W02发送人脸'

			imageName = data['imageName']
			imageUrl = imageName[1:len(imageName)]
			heiId = data['heiId']
			blackData = models.FaceBlackThread().selectById(heiId)
			bigface = models.FaceRecordThread().selectFaceById(imageUrl)
			models.FaceWarningThread().insert(bigface.FR_ID,blackData['fbId'])
			faceData = {}
			faceData['frBigImageulr'] = bigface.FR_BIG_IMAGEURL
			faceData['faceBlackImageUrl'] = blackData['fbImageUrl']
			faceData['frImageurl'] = imageUrl
			faceData['faceBlackName'] = blackData['fbName']
			sendData['list'].append(faceData)


	if len(sendData['list']):
		sendPro('W02',sendData)

def threadStartFace(msg):

	while True:

		global faceSocketIO
		# try:

		faceSocketIO = SocketIO(g_face_host, g_face_port, wait_for_connection=False)
		faceSocketIO.on('connect', on_face_connect)
		faceSocketIO.on('disconnect', on_face_disconnect)
		faceSocketIO.on('reconnect', on_face_reconnect)

		faceSocketIO.on('CC',on_face_CC)
		print '========faceSocketIO=============='
		faceSocketIO.wait()
		# except Exception, e:
		# 	logging.info(e)
		time.sleep(1)

def threadStartSocket(msg):

	while True:

		global socketIO
		try:

			socketIO = SocketIO(g_host, g_port,wait_for_connection=False)
			socketIO.on('connect', on_connect)
			socketIO.on('disconnect', on_disconnect)
			socketIO.on('reconnect', on_reconnect)
			socketIO.on('APP',on_APP)
			logging.info('--------程序启动--------') 
			socketIO.wait()
			print '========SocketIO=============='
			socketIO.wait()
		except Exception, e:
			logging.info(e)
		time.sleep(1)





# 拉取人脸黑名单实现方法
def pullFaceBlackHttp(macId):
    url = "http://cg.visualdeep.com:18200/CityInspectors/getFaceBlacklist.json"
    postDict = {}
    postDict["number"] = macId
    response = requests.post(url, json=postDict)
    logging.warn('get face black')
    logging.warn(response)
    res = {}
    res['code'] = 0
    try:
        if response.text != '' and response.text.encode('utf8') != '':
            jsonResp = json.loads(response.text.encode('utf8'))
            if jsonResp != None:
                fbList = jsonResp['faceBlackList']
                models.FaceBlackThread().insertFaceBlack(fbList)
                
                imgList = []
                for face in fbList:
                    it = {}
                    zjNum = face['fbZjNum']
                    imgRes = models.FaceBlackThread().selectImagesByZjnum(zjNum)
                    it['id'] = zjNum
                    it['name'] = face['fbName']
                    it['imageUrls'] = imgRes
                    imgList.append(it)

                sendData = {}
                sendData['checkId'] = macId
                sendData['points'] = 0.5
                sendData['imageList'] = imgList

                logging.warn('发送学习请求')
                logging.warn(sendData)
                sendFacePro('H10',sendData)
            else:
                res['code'] = -3
        else:
            res['code'] = -2
    except Exception, e:
        logging.error(repr(e))
        res['code'] = -1
        
    return json.dumps(res, ensure_ascii=False)


# 拉取车牌黑名单实现方法
def pullPlateBlackHttp(macId):
    url = "http://cg.visualdeep.com:18200/CityInspectors/getCarBlacklist.json"
    postDict = {}
    postDict["number"] = macId
    res = {}
    res['code'] = 0
    try:
        response = requests.post(url, json=postDict)
        if response.text != '' and response.text.encode('utf8') != '':
            jsonResp = json.loads(response.text.encode('utf8'))

            print(response)

            if jsonResp != None:
                models.PlateBlackThread().insertPlateBlack(
                    jsonResp['carBlackList'])
            else:
                res['code'] = -3
        else:
            res['code'] = -2
    except Exception, e:
        print repr(e)
        res['code'] = -1
        
    return json.dumps(res, ensure_ascii=False)

def uploadFaceImage():
	faceData = models.FaceRecordThread().selectUpload()
	print faceData
	sendData = {}
	sendData['cid'] = 'R1010'
	imageList = []


	for data in faceData['list']:
		imageData = {}
		imageData['lng'] =data['lng'].encode('utf8')
		imageData['lat'] =data['lat'].encode('utf8')
		imageData['recordId'] =data['uuid'].encode('utf8')

		with open("." + data['frImageUrl'], "rb") as rf:
			tmpr = rf.read()
			_struct = struct.Struct('%dB' % (len(tmpr)))
			bt = _struct.unpack(tmpr)
			imageData['smallImageByte'] = bt
		imageList.append(imageData)


	sendData['faceList'] = imageList


	with open("." + faceData['frBigImageUrl'], "rb") as brf:
		tmpr = brf.read()
		_struct = struct.Struct('%dB' % (len(tmpr)))
		bbt = _struct.unpack(tmpr)
		sendData['bigImageByte'] = bbt



	# print sendData

	# files['smallFile'] = open("." + faceData['list'][0]['frImageUrl'], "rb")
	# files['bigFile'] = open("." + faceData['frBigImageUrl'], "rb")
	re = requests.post(uploadUlr + '/SendRLImagesNewByte.json', json=sendData)
	if re.status_code == 200:
		models.FaceRecordThread().updataUpload(faceData['frBigImageUrl'])

def uploadPlate():
	plateData = models.PlateRecordThread().selectUpload()
	sendData = {}
	sendData['cid'] = plateData['deviceNumber']
	sendData['lng'] =plateData['lng']
	sendData['lat'] =plateData['lat']
	sendData['recordId'] =plateData['uuid']
	sendData['cpNO'] = base64.b64encode(plateData['cpNO'])

	with open("../" + plateData['prImageUrl'], "rb") as rf:
		tmpr = rf.read()
		_struct = struct.Struct('%dB' % (len(tmpr)))
		bt = _struct.unpack(tmpr)
		sendData['smallImageByte'] = bt

	with open("../" + plateData['prBigImageUrl'], "rb") as brf:
		tmpr = brf.read()
		_struct = struct.Struct('%dB' % (len(tmpr)))
		bbt = _struct.unpack(tmpr)
		sendData['bigImageByte'] = bbt

	# files = {}
	# files['bigFile'] = open("." + faceData['prBigImageUrl'], "rb")
	# files['smallFile'] = open("." + faceData['prImageUrl'], "rb")
	re = requests.post(uploadUlr + '/SendCPImagesNewByte.json', json=sendData)
	if re.status_code == 200:
		models.PlateRecordThread().updataUpload(plateData['prImageUrl'])

def uploadCPYJData():

	plateData = models.PlateWarningThread().selectUpload()


	sendData = {}
	sendData['cid'] = plateData['deviceNumber']
	sendData['method'] = 'car'
	sendData['recordId'] = plateData['recordId']
	sendData['cpNO'] = base64.b64encode(plateData['cpNO'])
	print sendData

	with open("../" + plateData['smallImage'], "rb") as rf:
		tmpr = rf.read()
		_struct = struct.Struct('%dB' % (len(tmpr)))
		bt = _struct.unpack(tmpr)
		sendData['smallImageByte'] = bt

	# files = {}
	# files['smallFile'] = open("." + plateData['smallFile'], "rb")

	re = requests.post(uploadUlr + '/SendYjNoticeNewByte.json', json=sendData)
	if re.status_code == 200:
		models.PlateWarningThread().updataUpload(plateData['id'])
def uploadFACEYJData():

	faceData = models.FaceWarningThread().selectUpload()
	sendData = {}
	sendData['cid'] = faceData['deviceNumber']
	sendData['method'] = 'face'
	sendData['recordId'] = faceData['recordId']
	sendData['faceBlackImageUrl'] = faceData['faceBlackImageUrl']

	with open("./" + faceData['smallImage'], "rb") as rf:
		tmpr = rf.read()
		_struct = struct.Struct('%dB' % (len(tmpr)))
		bt = _struct.unpack(tmpr)
		sendData['smallImageByte'] = bt
	re = requests.post(uploadUlr + '/SendYjNoticeNewByte.json', json=sendData)
	if re.status_code == 200:
		print faceData
		models.FaceWarningThread().updataUpload(faceData['id'])
	


def uploadFacePlateData(msg):

	while True:
		try:
			# uploadFaceImage()
			# uploadPlate()
			# uploadFACEYJData()
			# uploadCPYJData()
			time.sleep(3)
		except Exception as e:
			logging.error(e)
		
		

	

if __name__ == "__main__":
	# uploadFaceImage()
	# uploadPlate()
	# uploadFACEYJData()
	# uploadCPYJData()
	# uploadFaceImage()
	logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s(%(funcName)s)[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')


	print '========send success=============='



